﻿<%@ WebHandler Language="C#" Class="CommonHandler" %>

/*Description:公共接口
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer:Wangjh 
'create Date:20220310
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Text;
using System.Text.RegularExpressions;

public class CommonHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSContainerIBusiness m_ContainerObj = uMESBusinessFactory.instance.GetuLMSContainerObject();
    uLMSContainerPrintIBusiness printBusiness = uMESBusinessFactory.instance.GetuLMSPrintObject();
    uLMSCommonIBusiness commonBusiness = uMESBusinessFactory.instance.GetuLMSCommonObject();
    GZContainerBusiness gzBusiness = new GZContainerBusiness();
    uLMSStepTimeIBusiness stepTimeBusiness = uMESBusinessFactory.instance.GetuLMSStepTimeObject();
    LimitedCapacityBusiness m_LMObj = new LimitedCapacityBusiness();
    public void ProcessRequest(HttpContext context)
    {

        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getResourceBySpec"://获取设备信息
                    GetResourceBySpec(context);
                    break;
                case "viewPrintPage":
                    ViewPrintPage(context);
                    break;
                case "GetOperReason"://获取批次暂停原因
                    GetOperReason(context);
                    break;
                case "getFactory": //获取车间
                    GetFactory(context);
                    break;
                case "getWorkcenterByFactory": //获取工区
                    GetWorkcenterByFactory(context);
                    break;
                case "GetWorkcenterOfDefault": //获取工区（附带默认值）
                    GetWorkcenterOfDefault(context);
                    break;
                case "getTeamByWorkcenter": //获取班组
                    GetTeamByWorkcenter(context);
                    break;
                case "GetTeam": //获取班组
                    GetTeam(context);
                    break;
                case "GetProductSelect": //获取件号下拉数据（件号下拉组件）
                    GetProductSelectData(context);
                    break;
                case "GetWorkflowSelect"://获取工艺路线下拉数据（件号下拉组件）
                    GetWorkflowSelectData(context);
                    break;
                case "GetFirstCheckPrint"://获取首件检验单打印数据
                    GetFirstCheckPrint(context);
                    break;
                case "GetCommonMethodOperaLog"://获取功能操作日志
                    GetCommonMethodOperaLog(context);
                    break;
                case "DownloadExcelByRowsData"://导出页面表数据
                    DownloadExcelByRowsData(context);
                    break;
                case "GetERPWorkCeterData"://获取ERP工作中心数据
                    GetERPWorkCeterData(context);
                    break;
                case "GetERPFactoryData"://获取ERP分厂数据
                    GetERPFactoryData(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 导出页面表数据 add by zhangrj 20250815 
    /// </summary>
    /// <param name="context"></param>
    public void DownloadExcelByRowsData(HttpContext context)
    {
        DataTable dtRes = JsonConvert.DeserializeObject<DataTable>(context.Request["rowDatas"].ToString());
        if (dtRes.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "无数据" }));
            return;
        }
        foreach (DataColumn item in dtRes.Columns)
        {
            if (!Regex.IsMatch(item.ColumnName, "[\u4e00-\u9fa5]"))//是否包含中文
            {
                dtRes.Columns.Remove(item.ColumnName);//不包含则删除该列
            }
        }
        string fileName = context.Request["fileName"].ToString();
        byte[] bytes = uLMS_CommonFunction.DataTableExportToExcel(dtRes);
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AddHeader("fileDownload", "1");
        context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}{1}.xls", context.Server.UrlEncode(fileName), DateTime.Now.ToString("yyyyMMddHHmmssffff")));
        context.Response.AddHeader("Content-Length", bytes.Length.ToString());
        context.Response.AddHeader("Content-Type", "UTF-8");
        context.Response.Charset = "UTF-8";
        context.Response.ContentEncoding = Encoding.UTF8;
        context.Response.BinaryWrite(bytes);
        context.Response.Flush();
        context.Response.Close();
    }

    /// <summary>
    /// 获取功能操作日志 add by zhangrj 2023-12-23
    /// </summary> 
    /// <param name="context"></param>
    public void GetCommonMethodOperaLog(HttpContext context)
    {
        string parentID = context.Request["parentID"].ToString();
        string operaType = context.Request["operaType"].ToString();
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        result.DBTable = commonBusiness.GetCommonMethodOperaLogData(parentID, operaType);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取设备
    /// </summary>
    /// <param name="context"></param>
    public void GetResourceBySpec(HttpContext context)
    {
        if (context.Request["specId"] != null && string.IsNullOrWhiteSpace(context.Request["specId"].ToString()))
        {
            return;
        }
        var specId = "";
        foreach (string id in context.Request["specId"].ToString().Split(','))
        {
            specId += "'" + id + "',";
        }
        specId = specId.TrimEnd(',');
        var dt = m_LMObj.Aps_GetSpecResourceDt(specId);

        context.Response.Write(JsonConvert.SerializeObject(dt));
    }
    /// <summary>
    /// 获取首件检验单打印页面数据
    /// </summary>
    /// <param name="context"></param>
    public void GetFirstCheckPrint(HttpContext context)
    {
        string strHtml = string.Empty;
        List<Dictionary<string, object>> printSession = (List<Dictionary<string, object>>)context.Session["PrintInfo"];
        context.Session.Remove("PrintInfo");
        if (printSession != null && printSession.Count > 0)
        {
            for (int i = 0; i < printSession.Count; i++)
            {
                DataSet ds = printBusiness.GetFirstCheckPrintData(printSession[i]);
                if (ds.Tables["dtMain"].Rows.Count == 0)
                {
                    continue;
                }
                strHtml += i > 0 && !string.IsNullOrWhiteSpace(strHtml) ? GetPaging() : ""; //大于一条且不为空，则分页
                strHtml += GetPageHtml(ds);
            }
        }
        else
        {
            string ContainerId = context.Request["ContainerId"];
            string WorkflowId = context.Request["WorkflowId"];
            if (string.IsNullOrEmpty(ContainerId) || string.IsNullOrEmpty(WorkflowId))
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "刷新无效，请关闭后重新打印", Result = false }));
                return;
            }
            Dictionary<string, object> printInfo = new Dictionary<string, object>();
            printInfo["ContainerId"] = ContainerId;
            printInfo["WorkflowId"] = WorkflowId;
            DataSet ds = printBusiness.GetFirstCheckPrintData(printInfo);

            if (ds.Tables["dtMain"].Rows.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未找到热表批次", Result = false }));
                return;
            }
            strHtml += GetPageHtml(ds);
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, ReturnData = strHtml }));
    }

    private string GetPageHtml(DataSet ds)
    {
        int pageHeight = 0;
        DataTable dtMain = ds.Tables["dtMain"];//主数据
        DataTable dtCheckItem = ds.Tables["dtCheckItem"];//检测项
        StringBuilder strTotalHtml = new StringBuilder();
        foreach (DataRow dr in dtMain.Rows)
        {
            StringBuilder strHtml = new StringBuilder();
            int currHeight = 320;
            string checkDate = dr["checkdate"].ToString();
            if (!string.IsNullOrWhiteSpace(checkDate))
            {
                checkDate = DateTime.Parse(checkDate).ToString("yyyyMMdd");
            }
            string rightTitle = dr["productname"].ToString() + "-<span style='font-size:15px'>" + dr["specno"].ToString() + "</span>-" + checkDate + "-V" + dr["productrevision"].ToString();//格式：件号-日期-V件号版本
            strHtml.Append("<div style='width:100%;height:15px;margin-bottom:3px'><span style='float:right;font-size:13px'>" + rightTitle + "</span></div>");
            strHtml.Append("<table class='firstCheckTable'>");
            strHtml.Append("<tr class='headTitle'><td colspan='6'>首件检验单<br />(标档案号)</td></tr>");
            strHtml.Append("<tr><td colspan='2' style='width:220px'>工艺文件编号</td>  <td colspan='2' style='width:220px'>零件名称</td> <td colspan='2' style='width:220px'>批次顺序号</td>");
            strHtml.Append("<tr> <td colspan='2'>" + dr["process_no"].ToString() + "</td>");//工艺文件编号
            strHtml.Append("<td colspan='2'>" + dr["productdescription"].ToString() + "</td>");//零件名称
            strHtml.Append("<td colspan='2'>" + dr["firstcheckcontainerno"].ToString().Replace(dr["productname"].ToString() + "/", "") + "</td></tr>");//批次顺序号dr["containerno"].ToString()（改为取值首件批次号 edit by zhangrj 20250512）
            strHtml.Append(@"<tr><td colspan='2' style='width:220px'>工艺规程尺寸</td><td colspan='4'>
             <table class='checkItemTable'><tr><td style='width:180px'>自检结论</td>
             <td style='width:175px'>二检结论</td><td style='width:175px;border:0px'>专检结论</td></tr>
             </table></td></tr>");
            //插入检测项
            DataRow[] drs = dtCheckItem.Select("workflowstepid='" + dr["workflowstepid"].ToString() + "'");
            if (drs.Length > 0)
            {
                DataTable dtcheck = drs.CopyToDataTable().DefaultView.ToTable(true, "checkpointnotedis", "workcheckpointresultnotedis", "secondcheckpointnotedis", "checkpointresultnotedis");
                foreach (DataRow item in dtcheck.Rows)
                {
                    int h = 30;
                    int notebytes = Encoding.Default.GetByteCount(item["checkpointnotedis"].ToString());
                    int noteCount = (notebytes / 29) + 1;
                    if (noteCount > 1)
                    {
                        h += 15 * (noteCount - 1);//多一行高度增加15
                    }
                    strHtml.Append("<tr><td colspan='6'><div style='width:211px;float:left;height:" + h + "px;border-right:1px solid blue'>" + item["checkpointnotedis"].ToString() + "</div>");
                    strHtml.Append("<div style='width:164px;float:left;height:" + h + "px;border-right:1px solid blue'>" + item["workcheckpointresultnotedis"].ToString() + "</div>");
                    strHtml.Append("<div style='width:160px;float:left;height:" + h + "px;border-right:1px solid blue'>" + item["secondcheckpointnotedis"].ToString() + "</div>");
                    strHtml.Append("<div style='width:155px;float:left;height:" + h + "px;'>" + item["checkpointresultnotedis"].ToString() + "</div>");
                    strHtml.Append("</td></tr>");
                    currHeight += h;
                    //strHtml += "<tr><td colspan='2' style='width:220px'>" + item["checkpointnotedis"].ToString() + "</td>";//要求值
                    //strHtml += "<td colspan='4'> <table class='checkItemTable'><tr><td style='width:180px'>" + item["workcheckpointresultnotedis"].ToString() + "</td>";//自检值
                    //strHtml += " <td style='width:190px'>" + item["secondcheckpointnotedis"].ToString() + "</td>";//二检值
                    //strHtml += "<td style='width:175px;border:0px'>" + item["checkpointresultnotedis"].ToString() + "</td></tr> </table></td></tr>";//专检值
                }
            }

            strHtml.Append("<tr><td style='width:80px'>操作者</td><td style='width:150px'>" + dr["workername"].ToString() + "</td>");//操作者
            strHtml.Append("<td style='width:80px'>二检人员</td><td style='width:150px'>" + dr["secondername"].ToString() + "</td>");//二检人员
            strHtml.Append("<td style='width:80px'>检验员</td><td style='width:150px'>" + dr["checkername"].ToString() + "</td></tr>");//检验员
            strHtml.Append("<tr><td>结论</td><td colspan='2'></td>");//结论
            strHtml.Append("<td>日期</td><td colspan='2'>" + checkDate + "</td></tr></table>");//日期
            strHtml.Append("<div style='width:100%;height:60px'></div>");
            if (pageHeight + currHeight >= 1000)
            {
                strTotalHtml.Append(GetPaging());//分页
                pageHeight = 0;
            }
            strTotalHtml.Append(strHtml);
            pageHeight += currHeight;
        }
        return strTotalHtml.ToString();
    }
    /// <summary>
    /// 获取分页
    /// </summary>
    /// <returns></returns>
    private string GetPaging()
    {
        return "<div class='paging'></div>";
    }

    /// <summary>
    /// 获取批次是否暂停，以及暂停原因
    /// </summary>
    /// <param name="context"></param>
    public void GetOperReason(HttpContext context)
    {
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (paramDt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "没有选择批次" }));
            return;
        }
        string msg = "";
        foreach (DataRow item in paramDt.Rows)
        {
            if (commonBusiness.JudeContainerHold(item["containerId"].ToString(), ref msg))
            {
                msg = "批次：" + item["containerName"].ToString() + "已暂停，暂停原因：" + msg;
                break;//如果批次存在暂停，则结束
            }
        }
        if (!string.IsNullOrWhiteSpace(msg))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = msg }));
            return;
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "" }));
    }
    /// <summary>
    /// 获取车间
    /// </summary>
    /// <param name="context"></param>
    public void GetFactory(HttpContext context)
    {
        DataTable dt = commonBusiness.GetFactory(new Dictionary<string, string>());
        DataTable result = new DataTable();
        result.Columns.Add("FACTORYID");
        result.Columns.Add("FACTORYNAME");

        DataRow reRow = result.NewRow();
        reRow["FACTORYID"] = m_UserInfo.FactoryID;
        reRow["FACTORYNAME"] = m_UserInfo.Factory;

        result.Rows.Add(reRow);

        foreach (DataRow row in dt.Rows)
        {
            if (row["FACTORYID"].ToString() == m_UserInfo.FactoryID)
            {
                continue;
            }
            reRow = result.NewRow();
            reRow["FACTORYID"] = row["FACTORYID"];
            reRow["FACTORYNAME"] = row["FACTORYNAME"];

            result.Rows.Add(reRow);
        }
        result.AcceptChanges();
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取工区信息
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkcenterByFactory(HttpContext context)
    {
        DataTable wcdt = new DataTable();
        if (context.Request.Form.AllKeys.Contains("factoryId"))
        {
            wcdt = commonBusiness.GetWorkCenterByFacoryID(context.Request["factoryId"].ToString(), false);
        }
        else
        {
            wcdt = commonBusiness.GetWorkCenterByFacoryID(m_UserInfo.FactoryID, false);
        }
        DataRow[] drs = wcdt.Select(" notes is null or notes <>'已注销' ");
        if (drs.Length > 0)
        {
            wcdt = drs.CopyToDataTable();
        }
        context.Response.Write(JsonConvert.SerializeObject(wcdt));
    }
    /// <summary>
    /// 获取工区信息（附带默认值）
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkcenterOfDefault(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable wcdt = new DataTable();
        if (context.Request.Form.AllKeys.Contains("factoryId"))
        {
            wcdt = commonBusiness.GetWorkCenterByFacoryID(context.Request["factoryId"].ToString(), false);
        }
        else
        {
            wcdt = commonBusiness.GetWorkCenterByFacoryID(m_UserInfo.FactoryID, false);
        }
        DataRow[] drs = wcdt.Select(" notes is null or notes <>'已注销' ");
        if (drs.Length > 0)
        {
            wcdt = drs.CopyToDataTable();
        }
        result.DBTable = wcdt;
        if (wcdt.Select(string.Format("WORKCENTERID='{0}'", m_UserInfo.WorkCenterID)).Length != 0)
        {
            result.ReturnData = m_UserInfo.WorkCenterID;//默认当前人的工区ID
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取班组
    /// </summary>
    /// <param name="context"></param>
    public void GetTeamByWorkcenter(HttpContext context)
    {
        if (string.IsNullOrWhiteSpace(context.Request["workcenterId"].ToString()))
        {
            return;
        }
        var dt = commonBusiness.GetTeam(context.Request["workcenterId"].ToString());
        var re = dt.DefaultView.ToTable(true, "TEAMID", "TEAMNAME");
        context.Response.Write(JsonConvert.SerializeObject(re));
    }

    /// <summary>
    /// 获取班组
    /// </summary>
    /// <param name="context"></param>
    public void GetTeam(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "获取班组成功" };
        string workCenterId = context.Request["workCenterId"].ToString();
        if (string.IsNullOrWhiteSpace(workCenterId))
        {
            result.Result = false; result.Message = "没有工区";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DataTable dtTeam = commonBusiness.GetTeam(workCenterId);
        DataRow drteam = dtTeam.NewRow();
        drteam["TEAMID"] = "";
        drteam["TEAMNAME"] = "请选择";
        dtTeam.Rows.InsertAt(drteam, 0);//插入到第一行
        result.DBTable = dtTeam;
        if (dtTeam.Select(string.Format("TEAMID='{0}'", m_UserInfo.TeamID)).Length != 0)
        {
            result.ReturnData = m_UserInfo.TeamID;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取零件下拉选择
    /// </summary>
    /// <param name="context"></param>
    public void GetProductSelectData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "查询完成" };
        string productName = context.Request["productName"].ToString();
        DataTable dtProduct = (DataTable)commonBusiness.GetProductInfoLikeNameOrREVISION(productName);
        if (dtProduct.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "未查询到件号";
        }
        else
        {
            foreach (DataRow item in dtProduct.Rows)
            {
                if (item["PRODUCTID"].ToString() == item["REVOFRCDID"].ToString())
                {
                    item["PRODUCTNAME"] += "(默认)";
                }
            }
            dtProduct.AcceptChanges();
            result.DBTable = dtProduct;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取工艺规程下拉数据
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkflowSelectData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "数据过期，请重新登录" }));
            return;
        }
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "查询完成" };
        string productNames = context.Request["productName"].ToString();
        string workflowName = context.Request["workflowName"].ToString();
        DataTable dtWorkflow = new DataTable();
        if (string.IsNullOrWhiteSpace(productNames))
        {
            dtWorkflow = stepTimeBusiness.GetWorkflowOfNoRelevantToProduct(workflowName, m_UserInfo.FactoryID);
        }
        else
        {
            bool isThisFactory = bool.Parse(context.Request["isThisFactory"].ToString());
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string productName = productNames.Substring(0, productNames.IndexOf(":"));
            dic.Add("ProductName", productName);
            productNames = productNames.Replace(productName + ":", "");
            int len = productNames.IndexOf("(") == -1 ? productNames.Length : productNames.IndexOf("(");
            string productRev = productNames.Substring(0, len);
            dic.Add("ProductRev", productRev);
            if (isThisFactory)
            {
                dic.Add("FactoryID", m_UserInfo.FactoryID);
            }
            if (m_UserInfo.FactoryCode.Equals("603") || m_UserInfo.FactoryCode.Equals("628")) //add by longb 2023-06-19 试车、装配特殊查询
            {
                dic.Add("ZS", "");
            }
            dic.Add("WorkFlowIsUse", "0");//工艺路线是否有效（1有效；0无效） by duht 2024-8-15
            dtWorkflow = commonBusiness.GetWorkflowInfoWithOtherAndSubByProductInfo(dic, false, isThisFactory);
        }
        if (dtWorkflow.Rows.Count == 0)
        {
            result.Result = false;
            result.Message = "没有工艺";
        }
        result.DBTable = dtWorkflow;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 查看打印页面
    /// </summary>
    /// <param name="context"></param>
    public void ViewPrintPage(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;
        var oldPrintInfo = new Dictionary<string, string>();//一期项目打印用
        List<Dictionary<string, object>> printSession = new List<Dictionary<string, object>>();
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (string.IsNullOrWhiteSpace(paramDt.Rows[0]["CONTAINERID"].ToString()) && context.Request.Form.AllKeys.Contains("isReBiao"))//如果批次ID等于空，则是合卡批次（热表）
        {
            paramDt = m_ContainerObj.GetCombinateContainerDetailByName(paramDt.Rows[0]["containername"].ToString());
        }
        string containerIds = "";
        foreach (DataRow item in paramDt.Rows)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic["ContainerId"] = item["CONTAINERID"].ToString();
            dic["WorkflowId"] = item["WORKFLOWID"].ToString();
            dic["IsBlank"] = false;
            if (printSession.Contains(dic))//如果存在该批次，则跳过
            {
                continue;
            }
            printSession.Add(dic);
            containerIds += "'" + item["CONTAINERID"].ToString() + "',";
        }
        containerIds = containerIds.Trim(',');
        containerIds = "(" + containerIds + ")";
        //查询批次的类型信息，机加批次，叶片批次，热表批次
        var exuteEntity = new ExcuteEntity("container", ExcuteEntity.ExcuteTypeEnum.selectAll);
        exuteEntity.WhereFileds = new List<FieldEntity>();
        exuteEntity.strWhere = " and containerid in " + containerIds;

        DataTable dt = DatabaseHelper.QueryDataByEntity(exuteEntity);

        dt = dt.DefaultView.ToTable(true, "originalfactoryid", "ypcontainertype", "rbcontainertype");
        if (dt.Rows.Count > 1)
        {
            result.Message = "请选择同开卡车间批次再打印";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        context.Session["PrintInfo"] = printSession;
        string printStr = "";
        if (!string.IsNullOrWhiteSpace(dt.Rows[0]["rbcontainertype"].ToString()))
        {
            printStr = "/InSiteWebApplication/forms/Custom/ReBiao/RBProductWorkingPrintPage.html";
        }
        else if (!string.IsNullOrWhiteSpace(dt.Rows[0]["YPCONTAINERTYPE"].ToString()))
        {
            switch (dt.Rows[0]["YPCONTAINERTYPE"].ToString())
            {
                case "1":
                    printStr = "/InSiteWebApplication/forms/Custom/YePian/ContainerForgePrintForm.aspx";
                    break;
                case "2":
                    printStr = "/InSiteWebApplication/forms/Custom/YePian/ContainerMachiningPrintForm.aspx";
                    break;
                case "3":
                    printStr = "/InSiteWebApplication/forms/Custom/YePian/YPXianFengPiContainerInfoPrintForm.aspx";
                    break;
                case "4":
                    printStr = "/InSiteWebApplication/forms/Custom/YePian/ContainerSpecialPrintForm.aspx";
                    break;
                default:
                    break;
            }

        }
        else if (context.Request.Form.AllKeys.Contains("isReBiao"))
        {
            printStr = "/InSiteWebApplication/forms/Custom/ReBiao/RBProductWorkingPrintPage.html";
        }
        else
        {
            exuteEntity = new ExcuteEntity("Factory", ExcuteEntity.ExcuteTypeEnum.selectAll);
            exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("FactoryID", dt.Rows[0]["originalfactoryid"].ToString(), FieldEntity.FieldTypeEnum.Str) };

            var faDt = DatabaseHelper.QueryDataByEntity(exuteEntity);
            if (faDt.Rows[0]["FactoryName"].ToString().Contains("工装工具"))//是工装批次
            {
                printStr = "/InSiteWebApplication/forms/Custom/GongZhuang/GZContainerWorkflowPrintPage.html";
            }
            else
            {
                containerIds = containerIds.Replace("'", "").Trim('(').Trim(')');
                oldPrintInfo.Add("ContainerIDForPrint", containerIds);
                oldPrintInfo.Add("ConPrintType", "2");//默认是2
                if (context.Request["conPrintType"] != null)
                {
                    oldPrintInfo["ConPrintType"] = context.Request["conPrintType"].ToString();
                }
                if (context.Request.Form.AllKeys.Contains("isBomPrint"))
                {
                    if (context.Request["isBomPrint"].ToString() == "1")
                    {
                        oldPrintInfo.Add("IsBomPrint", "1");//只打印配套表
                    }
                }
                context.Session["PrintInfo"] = oldPrintInfo;
                printStr = "/InSiteWebApplication/forms/Custom/Print/ContainerInfoPrintForm.aspx";
            }
        }
        //add by longb 2024-08-06 基于vue页面打印使用
        if (context.Request.Form.AllKeys.Contains("isVue"))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { ReturnData = printStr, RowCount = "0", Code = "200", Message = "请求成功" }));
            return;
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, ReturnData = printStr }));
    }
    /// <summary>
    /// 获取ERP工作中心数据
    /// add by longb 2025-10-15
    /// </summary>
    /// <param name="context"></param>
    public void GetERPWorkCeterData(HttpContext context)
    {
        var factoryCode = context.Request["factoryCode"].ToString();
        var factoryName = context.Request["factoryName"].ToString();
        var workcenterName = context.Request["workcenterName"].ToString();
        var workcenterCode = context.Request["workcenterCode"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        var sql = @"SELECT * FROM erpworkcentercode c WHERE 1=1";
        if (!string.IsNullOrWhiteSpace(factoryName) && !factoryName.Equals("全部"))
        {
            sql += string.Format(" and c.factoryName like '%{0}%'", factoryName);
        }
        if (!string.IsNullOrWhiteSpace(factoryCode))
        {
            sql += string.Format(" and c.factoryCode like '%{0}%'", factoryCode);
        }
        if (!string.IsNullOrWhiteSpace(workcenterName))
        {
            sql += string.Format(" and c.workcenterName like '%{0}%'", workcenterName);
        }
        if (!string.IsNullOrWhiteSpace(workcenterCode))
        {
            sql += string.Format(" and c.workcenterCode like '%{0}%'", workcenterCode);
        }
        sql += " order by c.factoryName,c.workcenterCode";
        DataTable dt_Workcenter = DatabaseHelper.Query_ReturnDatTable(sql);
        DataRow newRow = dt_Workcenter.NewRow();
        newRow["WORKCENTERCODE"] = "";
        dt_Workcenter.Rows.InsertAt(newRow, 0);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, DBTable = dt_Workcenter }));
    }
    /// <summary>
    /// 获取ERP分厂数据
    /// add by longb 2025-10-15
    /// </summary>
    /// <param name="context"></param>
    public void GetERPFactoryData(HttpContext context)
    {
        DataTable dt_Workcenter = DatabaseHelper.Query_ReturnDatTable(@" SELECT '全部' factoryName FROM dual union SELECT distinct factoryName FROM erpworkcentercode c WHERE factoryName is not null");
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, DBTable = dt_Workcenter }));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }



}